package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private SystemUserService systemUserService;

    @Override
    public CaptchaVo getCaptcha() {
        // 创建一个SpecCaptcha对象，参数分别为宽度、高度和验证码长度
        SpecCaptcha captcha = new SpecCaptcha(130, 48, 4);
        // 生成验证码文本，并转换为小写(正确的验证码)
        String code = captcha.text().toLowerCase();
        // 将验证码图片转换为Base64编码的字符串
        String image = captcha.toBase64();
        // 生成一个唯一的键，用于存储验证码文本到Redis中
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID();
        // 将验证码文本存储到Redis中，并设置过期时间
        redisTemplate.opsForValue().set(key, code, RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);
        // 返回包含验证码图片和唯一键的CaptchaVo对象
        log.info("正确的验证码:" + code + " ;Base64编码的字符串:" + image);
        return new CaptchaVo(image, key);
    }

    @Override
    public String login(LoginVo loginVo) {
        //1.判断是否输入了验证码
        if (!StringUtils.hasText(loginVo.getCaptchaCode())) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }
        //2.校验验证码
        String code = redisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        if (code == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        if (!code.equals(loginVo.getCaptchaCode().toLowerCase())) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        redisTemplate.delete(loginVo.getCaptchaKey());
        //3.校验用户是否存在
        LambdaQueryWrapper<SystemUser> systemUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        systemUserLambdaQueryWrapper.eq(SystemUser::getUsername, loginVo.getUsername());
        SystemUser systemUser = systemUserService.getOne(systemUserLambdaQueryWrapper);
        if (systemUser == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        //4.校验用户是否被禁
        if (systemUser.getStatus() == BaseStatus.DISABLE) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        //5.校验用户密码
        if (!Objects.equals(systemUser.getPassword(), DigestUtils.md5Hex(loginVo.getPassword()))) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        //6.创建并返回TOKEN
        return JwtUtil.createToken(systemUser.getId(), systemUser.getUsername());
    }

    @Override
    public SystemUserInfoVo getSystemUserInfoById(Long userId) {
        // 根据用户ID从系统用户服务中获取用户实体
        SystemUser systemUser = systemUserService.getById(userId);
        // 创建一个系统用户信息传输对象实例
        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();
        // 将系统用户实体的名称赋值给信息传输对象
        systemUserInfoVo.setName(systemUser.getName());
        // 将系统用户实体的头像URL赋值给信息传输对象
        systemUserInfoVo.setAvatarUrl(systemUser.getAvatarUrl());
        // 返回填充了用户信息的信息传输对象
        return systemUserInfoVo;
    }
}